package com.zrrd.yunchmall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zrrd.yunchmall.order.client.ProductServiceClient;
import com.zrrd.yunchmall.order.entity.Order;
import com.zrrd.yunchmall.order.entity.OrderOperateHistory;
import com.zrrd.yunchmall.order.mapper.OrderMapper;
import com.zrrd.yunchmall.order.mapper.OrderOperateHistoryMapper;
import com.zrrd.yunchmall.order.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.yunchmall.user.entity.Admin;
import org.aspectj.weaver.ast.Or;
import org.bouncycastle.asn1.x509.qualified.RFC3739QCObjectIdentifiers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author YeKong
 * @since 2024-01-15
 */
@SuppressWarnings("all")
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    //注入一个商品服务的客户端实例，便于远程调用商品服务的接口
    @Autowired
    private ProductServiceClient productServiceClient;
    @Autowired
    private OrderItemServiceImpl orderItemService;
    @Autowired
    private OrderOperateHistoryMapper orderOperateHistoryMapper;
    //只能用于管理本地事务，第3步需要跨服服务完成，会产生分布式事务问题（Seata）
    @Transactional
    //@GlobalTransactional
    public void closeOrder(String ids, String note) {
        //1.修改订单状态
        List<Order> orderList = super.listByIds(Arrays.asList(ids.split(",")));
        orderList.forEach(order -> {
            order.setStatus(4);
            //2.记录日志
            OrderOperateHistory history = new OrderOperateHistory();
            history.setOrderId(order.getId());
            history.setOrderStatus(4);
            history.setNote(note);//设置备注
            history.setOperateMan("当前登录管理员");
            orderOperateHistoryMapper.insert(history);
            //3.释放库存
            List<Map<String, Object>> params = new LinkedList<>();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("order_id", order.getId());
            queryWrapper.select("product_id as productId",
                    "product_sku_id as skuId",
                    "product_quantity as quantity");
            params = orderItemService.listMaps(queryWrapper);
            productServiceClient.freeStock(params);
        });
        super.updateBatchById(orderList);//执行批量更新

    }

    @Transactional
    public void delivery(List<Map<String, Object>> params) {
        //1.循环遍历集合
        params.forEach(item -> {
            //2.设置条件，执行update操作
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id", item.get("orderId"));
            updateWrapper.set("status", 2);
            updateWrapper.set("delivery_company", item.get("deliveryCompany"));
            updateWrapper.set("delivery_sn", item.get("deliverySn"));
            updateWrapper.set("delivery_time", item.get("deliveryTime"));
            super.update(updateWrapper);

            //3.记录操作
            OrderOperateHistory history = new OrderOperateHistory();
            history.setOrderId(Long.valueOf(item.get("orderId").toString()));
            history.setOrderStatus(2);
            history.setNote("订单发货");//设置备注
            history.setOperateMan("当前登录管理员");
            orderOperateHistoryMapper.insert(history);
        });
    }

    @Override
    @Transactional
    public void remove(String ids, Admin admin) {
        //1.遍历订单id
        for (String orderId : ids.split(",")) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.select("status");
            queryWrapper.eq("id", orderId);
            Order order = super.getOne(queryWrapper);
            //订单存在，满足删除条件
            if (order != null && (order.getStatus() == 4 || order.getStatus() == 5)){
                //2.删除满足条件的订单（状态为4或5）
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id", orderId);
                updateWrapper.set("delete_status", 1);
                super.update(updateWrapper);
                //3.记录操作历史
                OrderOperateHistory history = new OrderOperateHistory();
                history.setOrderId(Long.valueOf(orderId));
                history.setOrderStatus(6);
                history.setNote("删除订单");//设置备注
                history.setOperateMan(admin.getId() + "," + admin.getUsername());
                orderOperateHistoryMapper.insert(history);
            }
        }
    }

    @Override
    public void updateReceiverInfo(Map<String, Object> params) {
        //1.修改信息
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", params.get("orderId"));
        updateWrapper.set("receiver_name", params.get("receiverName"));
        updateWrapper.set("receiver_phone", params.get("receiverPhone"));
        updateWrapper.set("receiver_post_code", params.get("receiverPostCode"));
        updateWrapper.set("receiver_province", params.get("receiverProvince"));
        updateWrapper.set("receiver_city", params.get("receiverCity"));
        updateWrapper.set("receiver_region", params.get("receiverRegion"));
        updateWrapper.set("receiver_detail_address", params.get("receiverDetailAddress"));
        super.update(updateWrapper);
        //2.添加操作历史
        OrderOperateHistory history = new OrderOperateHistory();
        history.setOrderId(Long.valueOf(params.get("orderId").toString()));
        history.setOrderStatus(Integer.valueOf(params.get("status").toString()));
        history.setNote("修改收件人信息");//设置备注
        history.setOperateMan("登录人信息");
        orderOperateHistoryMapper.insert(history);
    }

    @Override
    @Transactional
    public void updateMoneyInfo(@RequestBody Map<String, Object> params, Admin admin) {
        Order order = super.getById(params.get("orderId").toString());
        float newFreightAmout = 0f;
        if (params.get("freightAmount") != null) {
            newFreightAmout = Float.valueOf(params.get("freightAmount").toString());
        }
        float newDiscountAmount = 0f;
        if (params.get("discountAmount") != null) {
            newDiscountAmount = Float.valueOf(params.get("discountAmount").toString());
        }
        order.setFreightAmount(BigDecimal.valueOf(newFreightAmout));
        order.setDiscountAmount(BigDecimal.valueOf(newDiscountAmount));
        //实际的支付金额
        float totalAmount = order.getTotalAmount().floatValue();
        float promotionAmount = order.getPromotionAmount().floatValue();
        float integrationAmount = order.getIntegrationAmount().floatValue();
        float couponAmount = order.getCouponAmount().floatValue();
        float payAmount = totalAmount + newFreightAmout
                - newDiscountAmount
                - promotionAmount
                - integrationAmount
                - couponAmount;
        order.setPayAmount(BigDecimal.valueOf(payAmount));
        super.updateById(order);

        OrderOperateHistory history = new OrderOperateHistory();
        history.setOrderId(order.getId());
        history.setOrderStatus(Integer.valueOf(params.get("status").toString()));
        history.setNote("修改收件人信息");//设置备注
        history.setOperateMan(admin.getId() + " , " + admin.getUsername());
        orderOperateHistoryMapper.insert(history);
    }


}
